'use client'

import type { Layer } from '@shared/schema'
import { AlertCircle, Check, Copy, FileCode } from 'lucide-react'
import { useEffect, useState } from 'react'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'

interface JsonEditorProps {
  layers: Layer[]
  onLayersUpdate: (layers: Layer[]) => void
}

export function JsonEditor({ layers, onLayersUpdate }: JsonEditorProps) {
  const [jsonText, setJsonText] = useState('')
  const [error, setError] = useState<string | null>(null)
  const [copied, setCopied] = useState(false)
  const [hasChanges, setHasChanges] = useState(false)

  // 初始化 JSON 文本
  useEffect(() => {
    setJsonText(JSON.stringify(layers, null, 2))
    setError(null)
    setHasChanges(false)
  }, [layers])

  // 处理 JSON 变化
  const handleJsonChange = (value: string) => {
    setJsonText(value)
    setError(null)
    setHasChanges(true)
  }

  // 应用 JSON 更改
  const handleApply = () => {
    try {
      const parsed = JSON.parse(jsonText)

      // 验证是否是数组
      if (!Array.isArray(parsed)) {
        throw new Error('JSON 必须是一个数组')
      }

      // 基本验证每个图层
      for (const [index, layer] of parsed.entries()) {
        if (!layer.id || !layer.type) {
          throw new Error(`图层 ${index} 缺少必需的 id 或 type 字段`)
        }
        if (!layer.position || typeof layer.position.x !== 'number' || typeof layer.position.y !== 'number') {
          throw new Error(`图层 ${index} 的 position 字段无效`)
        }
      }

      onLayersUpdate(parsed)
      setError(null)
      setHasChanges(false)
    }
    catch (err: any) {
      setError(err.message || 'JSON 格式无效')
    }
  }

  // 复制到剪贴板
  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(jsonText)
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    }
    catch (err) {
      console.error('复制失败:', err)
    }
  }

  // 格式化 JSON
  const handleFormat = () => {
    try {
      const parsed = JSON.parse(jsonText)
      setJsonText(JSON.stringify(parsed, null, 2))
      setError(null)
    }
    catch (err: any) {
      setError(err.message || 'JSON 格式无效，无法格式化')
    }
  }

  // 重置
  const handleReset = () => {
    setJsonText(JSON.stringify(layers, null, 2))
    setError(null)
    setHasChanges(false)
  }

  return (
    <div className="flex flex-col h-full bg-background">
      {/* Header */}
      <div className="flex items-center justify-between p-4 border-b bg-card">
        <div className="flex items-center gap-2">
          <FileCode className="w-5 h-5 text-primary" />
          <h2 className="text-lg font-semibold">JSON 编辑器</h2>
          <span className="text-sm text-muted-foreground">
            {layers.length} 个图层
          </span>
        </div>
        <div className="flex items-center gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={handleFormat}
          >
            格式化
          </Button>
          <Button
            variant="outline"
            size="sm"
            onClick={handleCopy}
          >
            {copied ? (
              <>
                <Check className="w-4 h-4 mr-2" />
                已复制
              </>
            ) : (
              <>
                <Copy className="w-4 h-4 mr-2" />
                复制
              </>
            )}
          </Button>
          {hasChanges && (
            <>
              <Button
                variant="outline"
                size="sm"
                onClick={handleReset}
              >
                重置
              </Button>
              <Button
                size="sm"
                onClick={handleApply}
              >
                应用更改
              </Button>
            </>
          )}
        </div>
      </div>

      {/* Error Alert */}
      {error && (
        <div className="p-4 border-b">
          <Alert variant="destructive">
            <AlertCircle className="w-4 h-4" />
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        </div>
      )}

      {/* JSON Editor */}
      <div className="flex-1 p-4 overflow-hidden">
        <Textarea
          value={jsonText}
          onChange={(e) => handleJsonChange(e.target.value)}
          className="w-full h-full font-mono text-sm resize-none"
          placeholder="JSON 数据..."
          spellCheck={false}
        />
      </div>

      {/* Footer */}
      <div className="flex items-center justify-between p-4 border-t bg-card text-sm text-muted-foreground">
        <div>
          提示: 编辑 JSON 后点击"应用更改"以更新图层数据
        </div>
        <div>
          {hasChanges && (
            <span className="text-orange-500 font-medium">未保存的更改</span>
          )}
        </div>
      </div>
    </div>
  )
}

